﻿using Company.Database.Entities;
using Company.Database.Interfaces;
using Company.Demo.Views;
using Company.Share;
using Company.Share.Message;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ToolKit.Mvvm.Attributes;
using ToolKit.Mvvm.Bindings;
using ToolKit.Mvvm.Enums;
using ToolKit.Mvvm.Events;

namespace Company.Demo.ViewModels
{
    [DependenceInjection(Lifetime.Singleton)]
    internal class ShellViewModel : ViewModelBase
    {
        private string title = "IOC框架开发实战课程";
        public string Title2 { get => title; set => SetProperty(ref title, value); }

        [AutoNotify]
        public string Title { get; set; }
        public ICommand LoadedCommand { get; }

        private LoginView LoginView { get; }
        private MainView MainView { get; }
        private IUserRepository UserRepository { get; }
        private ContentControl container = null;

        public ISession Session { get; }
        public ShellViewModel(LoginView loginView,
            MainView mainView,
            IUserRepository userRepository,
            ISession session)
        {
            LoginView = loginView;
            MainView = mainView;
            UserRepository = userRepository;
            Session = session;
            LoadedCommand = new RelayCommand<ContentControl>(view => 
            {
                container = view;
                view.Content = loginView;
            });
            
            Task.Factory.StartNew(() =>
            {
                User user = UserRepository.GetAll().FirstOrDefault();
                if (user == null)
                {
                    user = new User();
                    user.UserName = "admin";
                    user.Password = "12345678";
                    user.InsertDate = DateTime.Now;
                    int count = UserRepository.Insert(user);
                    if(count > 0)
                    {
                        MessageBox.Show("首次运行系统，注册admin管理员\r\n密码12345678");
                    }
                }
                Task.Delay(1000).Wait();
                Title = "IOC框架开发实战课程 - 讲师:重庆教主";
            });

            //订阅登录成功事件
            EventBus.Default.Subscribe<LoginMessage>((sender, message) =>
            {
                MessageBox.Show($"登录成功\r\nsender:{sender} \r\nmessage: {message}");
                Session.CurrentUser = message.Value;
                container.Content = MainView;
            });

            //EventBus.Default.Subscribe<LoginMessage>(callback);



            
        }

        private void callback(object arg1, LoginMessage arg2)
        {
            EventBus.Default.UnSubscribe<LoginMessage>(callback);
        }
    }
}
